import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import Header from './components/headerTitle';
import SubItem from './components/treeSubItem';
import ChildItem from './components/treeChildItem';
import { fetchTreeData } from '@/service/api';
import styles from './index.less';

export default () => {
  const [treeData, setTreeData] = useState([]); // TODO defaultCollapsed

  useEffect(() => {
    fetchTreeData().then((list) => {
      if (_.isArray(list)) {
        setTreeData(list);
      }
    });
  }, []);

  const renderTree = (list, pList = []) =>
    list?.map(({ id, children, ...restProps }) =>
      children && children.length ? (
        <SubItem key={id} id={id} pList={pList} {...restProps}>
          {renderTree(children, [...pList, { id, ...restProps }])}
        </SubItem>
      ) : (
        <ChildItem key={id} id={id} pList={pList} {...restProps} />
      ),
    );

  return (
    <div className={styles.treeBox}>
      <Header />
      {renderTree(treeData)}
    </div>
  );
};
